import java.awt.image.RenderedImage;
import java.util.Random;

public class GeneticPlayer
{
	int serial = 0;
	Random rand = new Random();
	/*
	 * need: genome to hold move answers which piece to play, X or O
	 */

	final int genomeSize = 19683;
	// sqrt(19683) = 140, so a 141x141 image can represent the genome
	static TTTGame thisGame = null;
	int movs = 0;

	public int[] genome = new int[genomeSize]; // 3^9 genes for this particular
	// game
	static int playerPiece = 2; // start w/ O by default

	public void setGame(TTTGame inGame)
	{
		thisGame = inGame;
	}

	public int getPlayerPiece()
	{
		return playerPiece;
	}

	public void setPlayerPiece(int playerPiece)
	{
		GeneticPlayer.playerPiece = playerPiece;
	}

	public GeneticPlayer()
	{
		thisGame = new TTTGame();
	}

	public GeneticPlayer(TTTGame inGame)
	{
		thisGame = inGame;
		// randomize the genome
		randomizeGenome();
	}

	public void randomizeGenome()
	{
		for (int i = 0; i < genomeSize; i++)
		{
			// set genome[i] to a random number between 0 and 8
			genome[i] = rand.nextInt(9);
			// System.out.println(genome[i]);
		}
	}

	// need genome decoding function
	public boolean makeMove()
	{
		// TODO: write some code to decode the genetic algorithm
		// decode genome, figure out what should be done, and decide if it can
		// be done

		// do some stuff to decide if this genetic move can be made

		// extract the move from the genome
		int move = decode(genome);
		// new popupNotice(0, 60, String.valueOf(move)).start();
		// new popupNotice(0, 100,
		// String.valueOf(thisGame.canPlace(move))).start();

		// if this move can be made
		if (thisGame.canPlace(move))
		{
			return thisGame.placePiece(move, playerPiece);
		}
		else
		{
			// this piece can not be placed here!
			// try a new piece and then correct the genome
			genome[thisGame.boardState()] = findValidMove();
			if (thisGame.placePiece(findValidMove(), playerPiece))
			{
				return true;
			}
			else
			{
				// the game ended somehow?
				new popupNotice(40, 40, "Congratulations!").start();
				// System.exit(3);
				return false;
			}
			// return thisGame.placePiece(findValidMove(), playerPiece);
		}

		// if (findValidMove() == -1)
		// {
		// return false;
		// }

		// return thisGame.placePiece(findValidMove(), playerPiece);

	}

	private int decode(int[] genome2)
	{
		return genome[thisGame.boardState()];
		// TODO Auto-generated method stub
	}

	public static int findValidMove()
	{
		for (int i = 0; i < 9; i++)
		{
			if (thisGame.canPlace(i))
			{
				return i;
			}
		}
		return -1;
	}

	public TTTGame getGame()
	{
		return thisGame;
	}

	public void setGenome(int[] tempGenome)
	{
		genome = tempGenome;

	}
}
